#include "graphmodelslist.h"

GraphModelsList::GraphModelsList()
{
    graphNum = 0;
}

GraphModelsList::~GraphModelsList()
{
}

bool GraphModelsList::addGraphsToList(QString textEditData)
{
    QStringList numList = textEditData.simplified().split(" ");

    if (!CheckCorrectStrList(numList)) {
        QMessageBox::critical(0, "Error", "Text field contains invalid characters.");
        return false;
    }
    if (!CheckCorrectNumCount(numList)) {
        QMessageBox::critical(0, "Error", "Not enough symbols in text field.");
        return false;
    }

    bool ok;
    for (int i = 0; i < numList.count(); ++i)
    {
        GraphModel tempGraphModel;
        int vertex = numList.at(i).toInt(&ok, 10);
        int *adjMatrix  = new int[vertex * vertex];
        if (!adjMatrix) {
            QMessageBox::critical(0, "Critical", "Failed to allocate memory for matrix. Missing.");
            continue;
        }
        for (int j = i + 1, n = 0; j <= vertex * vertex + i; ++j, ++n)
            adjMatrix[n] = numList.at(j).toInt(&ok, 10);
        i += vertex * vertex;
        tempGraphModel.SetGraphModel(adjMatrix, vertex);
        GraphsList << tempGraphModel;
    }
    return true;
}

bool GraphModelsList::CheckCorrectStrList(QStringList numList)
{
    for (int i = 0; i < numList.count(); ++i)
        for (int j = 0; j < numList.at(i).size(); ++j)
            if (!numList.at(i)[j].isDigit()) return false;
    return true;
}

bool GraphModelsList::CheckCorrectNumCount(QStringList numList)
{
    bool ok;
    for (int i = 0, j; i < numList.size() ; ++i)
    {
        j = numList.at(i).toInt(&ok, 10);
        if (i + j * j > numList.size() - 1) return false;
        i += j * j;
    }
    return true;
}

GraphModel GraphModelsList::getGraphModel()
{
    return GraphsList.at(graphNum);
}

void GraphModelsList::increaseGraphNum()
{
    if (++graphNum > GraphsList.size() - 1)
        graphNum = 0;
}

void GraphModelsList::decreaseGraphNum()
{
    if (--graphNum < 0)
        graphNum = GraphsList.size() - 1;
}

int GraphModelsList::getGraphNum()
{
    return graphNum;
}

int GraphModelsList::size()
{
    return GraphsList.size();
}

bool GraphModelsList::isEmpty()
{
    if (GraphsList.isEmpty()) return true;
    else return false;
}
